package com.jzlin.funhub.admin.service.system;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzlin.funhub.admin.mapper.UserFollowMapper;
import com.jzlin.funhub.admin.model.entity.UserFollow;
import com.jzlin.funhub.admin.model.req.UserFollowPageReq;
import com.jzlin.funhub.admin.model.req.UserFollowReq;
import com.jzlin.funhub.admin.model.req.UserFollowedPageReq;
import com.jzlin.funhub.admin.model.resp.UserFollowedPageResp;
import com.jzlin.funhub.framework.common.consts.BaseConst;
import com.jzlin.funhub.framework.core.exception.AppException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户关注表 服务实现类
 * </p>
 *
 * @author jzlin
 * @since 2025-08-13
 */
@Service
public class UserFollowService extends ServiceImpl<UserFollowMapper, UserFollow> {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 关注/取消关注用户
     *
     * @param req
     */
    @Transactional
    public void followUser(UserFollowReq req) {
        Long loginUserId = StpUtil.getLoginIdAsLong();
        if (loginUserId.equals(req.getUserId())) {
            throw new AppException("您无法关注自己哦！");
        }
        if (req.getFlag()) {
            int row = this.baseMapper.followUser(loginUserId, req.getUserId());
            if (row > 0) {
                sysUserService.updateFollowedCount(req.getUserId(), true);
                sysUserService.updateFollowCount(loginUserId, true);
            }
        } else {
            boolean success = this.update()
                    .eq("followed_user_id", req.getUserId())
                    .eq("user_id", loginUserId)
                    .set("del", BaseConst.FLAG_TRUE).update();
            if (success) {
                sysUserService.updateFollowedCount(req.getUserId(), false);
                sysUserService.updateFollowCount(loginUserId, false);
            }
        }
    }

    /**
     * 检查批量用户是否已被关注
     * @param userId 关注人id
     * @param checkUserIdList 待检查的被关注用户id
     * @return 已被关注的用户id
     */
    public List<Long> filterHasFollow(Long userId, List<Long> checkUserIdList) {
        if (CollUtil.isEmpty(checkUserIdList)) {
            return Collections.emptyList();
        }
        List<UserFollow> queryRet = this.query().select("followed_user_id")
                .eq("del", Boolean.FALSE)
                .eq("user_id", userId)
                .in("followed_user_id", checkUserIdList).list();
        return queryRet.stream().map(UserFollow::getFollowedUserId).collect(Collectors.toList());
    }

    /**
     * 检查用户是否已被关注
     * @param userId 关注人
     * @param followedUserId 被关注人
     * @return true已关注
     */
    public boolean checkUserHasFollow(Long userId, Long followedUserId) {
        return this.query().select("followed_user_id")
                .eq("del", Boolean.FALSE)
                .eq("user_id", userId)
                .eq("followed_user_id", followedUserId).exists();
    }

    /**
     * 查询粉丝列表
     * @return
     */
    public Page<UserFollowedPageResp> queryPageUserFollowed(UserFollowedPageReq req) {
        IPage<?> page = new Page<>(req.getCurrent(), req.getSize());
        Page<UserFollowedPageResp> result = baseMapper.queryPageUserFollowed(req.getUserId(), page);
        //登录用户是否已关注
        setHasFollow(result);
        return result;
    }

    /**
     * 查询用户关注列表
     * @return
     */
    public Page<UserFollowedPageResp> queryPageUserFollow(UserFollowPageReq req) {
        IPage<?> page = new Page<>(req.getCurrent(), req.getSize());
        Page<UserFollowedPageResp> result = baseMapper.queryPageUserFollow(req.getUserId(), page);
        //登录用户是否已关注
        setHasFollow(result);
        return result;
    }

    private void setHasFollow(Page<UserFollowedPageResp> pageRecords) {
        if (CollUtil.isEmpty(pageRecords.getRecords())) {
            return;
        }
        if (!StpUtil.isLogin()) {
            return;
        }
        //登录用户是否已关注
        List<Long> hasFollowUserId = filterHasFollow(StpUtil.getLoginIdAsLong(), pageRecords.getRecords().stream().map(UserFollowedPageResp::getId).collect(Collectors.toList()));
        pageRecords.getRecords().stream().filter(records -> hasFollowUserId.contains(records.getId())).forEach(records -> records.setHasFollow(true));
    }
}
